#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2022/10/17 21:36
# @Author  : when
# @File    : chrome_driver.py
# @Description : url收集器
import sys

from loguru import logger
from selenium import webdriver
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager


class ChromeDriver:
    """
    url收集器
    """

    def __init__(self):
        self.driver = None
        # selenium 4.x
        self.chrome_options = webdriver.ChromeOptions()
        self.chrome_service = Service(executable_path=ChromeDriverManager().install())

    def init_driver(self):
        self.driver = webdriver.Chrome(service=self.chrome_service, options=self.chrome_options)

    def init_options(self, options: list):
        for o in options:
            self.chrome_options.add_argument(o)
        if sys.platform == "linux":
            # linux必须开启无沙盒模式运行，否则报错
            self.chrome_options.add_argument("--no-sandbox")
        # 反爬：屏蔽自动化受控提示
        self.chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
        # 反爬：禁用拓展
        # self.chrome_options.add_experimental_option('useAutomationExtension', False)
        self.chrome_options.add_argument("--disable-blink-features=AutomationControlled")

    def init_proxy_ext(self, ext_file_path):
        """
        设置认证代理
        :return:
        """
        self.chrome_options.add_extension(ext_file_path)

    def check_proxy(self, retry_num=0):
        """
        检测代理是否可用
        :param retry_num: 不可用重新获取次数
        :return:
        """
        use_flag = False
        for i in range(retry_num + 1):
            try:
                self.driver.get("https://2022.ip138.com/")
                pre_of_element = expected_conditions.presence_of_element_located((By.XPATH, "/html/body/p[1]"))
                proxy_addr = WebDriverWait(self.driver, 3).until(pre_of_element)
                assert proxy_addr, "检测代理时，页面加载失败..."
                logger.info(f"浏览器driver出口代理({proxy_addr.text})")
            except Exception as e:
                error_str = str(e).split('\n')[0]
                if i != retry_num:
                    logger.warning(f"代理不可用尝试第{i + 1}次重新获取... 错误信息：{type(e)} {error_str}")
                continue
            use_flag = True
            break
        return use_flag

    # def http_get(self, url: str):
    #     """
    #     爬取url对应的网页源码
    #     :param url: 待爬取url
    #     :return:
    #     """
    #     self.driver.get(url)
    #     # if wait_time > 0:
    #     #     # self.driver.implicitly_wait(wait_time)
    #     #     time.sleep(wait_time)
